package com.aji.controller;

import com.aji.dto.LoginDto;
import com.aji.entity.User;
import com.aji.properties.JwtProperties;
import com.aji.result.Result;
import com.aji.service.LoginService;
import com.aji.utills.JwtUtil;
import com.aji.vo.LoginVo;
import com.aji.vo.UserInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@RestController
@Slf4j
@Api(tags = "登录")
public class LoginController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private JwtProperties jwtProperties;

    @ApiOperation("登录")
    @PostMapping("/login")
    public Result<LoginVo> login(@RequestBody LoginDto loginDto){
        log.info("员工登录：{}", loginDto);
        User user = loginService.login(loginDto);
        //登录成功后，生成jwt令牌
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("userId", user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);
        LoginVo loginVo = LoginVo.builder()
                .id(user.getId())
                .userName(user.getUsername())
                .name(user.getName())
                .token(token)
                .build();

        return Result.success(loginVo);
    }

    @ApiOperation("获取 用户权限信息")
    @GetMapping("/userInfo")
    public Result userInfo(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User user = loginService.getByUserId((Long) authentication.getPrincipal());
        UserInfo userInfo = UserInfo.builder()
                .permission(loginService.getRoleById(user.getId())).build();
        return Result.success(userInfo);
    }
}
